class Definition < ActiveRecord::Base
  has_many :definition_parts
  after_update :save_definition_parts
  attr_accessor :fetched_number
  validates_associated :definition_parts
  
  def fetch
    fetched_parts = Array.new
    definition_parts.each { |p| fetched_parts << p.fetch }
    @fetched_number = fetched_parts.join(separator)
    return @fetched_number
  end
  
  def constants=(attributes)
    attributes.each do |a|
      if a[:id].blank?
        definition_parts << Constant.create(a)
      else
        definition_part = definition_parts.detect { |t| t.id == a[:id].to_i }
        definition_part.attributes = a
      end
    end
  end
  
  def constants
    definition_parts.find(:all, :conditions => [ "type = ?", "Constant"])
  end
  
  def sequences
    definition_parts.find(:all, :conditions => [ "type = ?", "Sequence"])
  end
  
  def sequences=(attributes)
    attributes.each do |a|
      if a[:id].blank?
        a[:position] = a[:position].to_i - a[:inc].to_i 
        definition_parts << Sequence.create(a)
      else
        definition_part = definition_parts.detect { |t| t.id == a[:id].to_i }
        definition_part.attributes = a
      end
    end
  end
  
#    def definition_parts_attributes=(definition_parts_attributes)
#    definition_parts_attributes.each do |a|
#      if a[:id].blank?
#        case a[:type] #rubify later
#          when "Constant": definition_parts << Constant.create(a)
#          when "Sequence": definition_parts << Sequence.create(a)
#          #definition_parts.build(a)
#        end
#      else
#        definition_part = definition_parts.detect { |t| t.id == a[:id].to_i }
#        definition_part.attributes = a
#      end
#    end
#  end
  
  def save_definition_parts
    definition_parts.each do |d|
      if d.should_destroy?
        d.destroy
      else
        d.save(false)
      end
    end
  end
end
